<template>
  <view class="config-edit-page">
    <!-- 表单内容 -->
    <view class="form-content">
      <uni-forms
          ref="formRef"
          :modelValue="form"
          :rules="rules"
          labelWidth="100px">

        <uni-forms-item label="参数名称" name="configName" required>
          <uni-easyinput
              v-model="form.configName"
              placeholder="请输入参数名称"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="参数键名" name="configKey" required>
          <uni-easyinput
              v-model="form.configKey"
              placeholder="请输入参数键名"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="参数键值" name="configValue" required>
          <uni-easyinput
              v-model="form.configValue"
              placeholder="请输入参数键值"
              :clearable="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>

        <uni-forms-item label="系统内置" name="configType">
          <BottomSelect
              v-model="form.configType"
              :options="configTypeOptions"
              :disabled="!canEdit"
              placeholder="请选择系统内置"
              title="选择系统内置">
          </BottomSelect>
        </uni-forms-item>

        <uni-forms-item label="备注" name="remark">
          <uni-easyinput
              v-model="form.remark"
              type="textarea"
              placeholder="请输入备注信息"
              :auto-height="true"
              :disabled="!canEdit">
          </uni-easyinput>
        </uni-forms-item>
      </uni-forms>
    </view>

    <!-- 底部操作按钮 -->
    <view class="footer-actions">
      <view class="action-buttons">
        <view
            v-if="!isView"
            class="cancel-btn"
            @click="handleBack">
          取消
        </view>
        <view
            v-if="!isView"
            class="submit-btn"
            @click="handleSubmit">
          {{ pageType === 'add' ? '确认新增' : '保存修改' }}
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import {computed, getCurrentInstance, reactive, ref} from 'vue'
import {onLoad} from '@dcloudio/uni-app'
import {addConfig, getConfig, updateConfig} from '@/api/system/config'
import BottomSelect from '@/components/select/BottomSelect.vue'

// 使用统一组件导入

const {proxy} = getCurrentInstance()

// 页面参数
const mode = ref('add')
const configId = ref('')
const title = ref('新增参数')
const submitting = ref(false)

// 计算属性
const isEdit = computed(() => mode.value === 'edit')
const isView = computed(() => mode.value === 'view')
const isAdd = computed(() => mode.value === 'add')
const canEdit = computed(() => mode.value === 'add' || mode.value === 'edit')

// 表单数据
const form = reactive({
  configId: undefined,
  configName: '',
  configKey: '',
  configValue: '',
  configType: 'N',
  remark: ''
})

// 表单验证规则
const rules = reactive({
  configName: {
    rules: [
      {required: true, errorMessage: '请输入参数名称'},
      {minLength: 2, errorMessage: '参数名称至少2个字符'},
      {maxLength: 100, errorMessage: '参数名称不能超过100个字符'}
    ]
  },
  configKey: {
    rules: [
      {required: true, errorMessage: '请输入参数键名'},
      {pattern: /^[a-zA-Z0-9._-]+$/, errorMessage: '参数键名只能包含字母、数字、点、下划线和横线'},
      {minLength: 2, errorMessage: '参数键名至少2个字符'},
      {maxLength: 100, errorMessage: '参数键名不能超过100个字符'}
    ]
  },
  configValue: {
    rules: [
      {required: true, errorMessage: '请输入参数键值'},
      {maxLength: 2000, errorMessage: '参数键值不能超过2000个字符'}
    ]
  }
})

// 选项数据
const configTypeOptions = ref([
  {value: 'Y', text: '是'},
  {value: 'N', text: '否'}
])

const formRef = ref()

// 计算属性
const getConfigTypeLabel = computed(() => {
  return (type) => {
    const option = configTypeOptions.value.find(item => item.value === type)
    return option ? option.text : '未知'
  }
})

// ==================== 修复：使用 onLoad 生命周期钩子 ====================
onLoad((options) => {

  mode.value = options.mode || 'add'

  if ((options.mode === 'edit' || options.mode === 'view') && options.configId) {
    configId.value = options.configId
    title.value = options.mode === 'edit' ? '编辑参数' : '查看参数'
    getConfigInfo()
  } else {
    title.value = '新增参数'
  }

  // 设置页面标题
  uni.setNavigationBarTitle({
    title: title.value
  })
})

// 获取参数信息
async function getConfigInfo() {
  try {
    const response = await getConfig(configId.value)
    if (response.code === 200) {
      Object.assign(form, response.data)
    } else {
      proxy.$modal.showToast(response.msg || '获取参数信息失败')
    }
  } catch (error) {
    console.error('获取参数信息失败:', error)
    proxy.$modal.showToast('获取参数信息失败')
  }
}

// 提交表单
async function handleSubmit() {
  try {
    // 表单验证
    const valid = await formRef.value.validate()
    if (!valid) return

    submitting.value = true

    let response
    if (isEdit.value) {
      response = await updateConfig(form)
    } else {
      response = await addConfig(form)
    }

    if (response.code === 200) {
      proxy.$modal.showToast(isEdit.value ? '修改成功' : '新增成功')
      setTimeout(() => {
        handleBack()
      }, 1500)
    } else {
      proxy.$modal.showToast(response.msg || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    proxy.$modal.showToast('操作失败')
  } finally {
    submitting.value = false
  }
}

// 取消操作
function handleCancel() {
  proxy.$modal.confirm('确定要取消吗？未保存的内容将丢失。').then(() => {
    handleBack()
  })
}

// 返回上一页
function handleBack() {
  uni.navigateBack()
}
</script>

<style lang="scss" scoped>
.config-edit-page {
  min-height: 100vh;
  background: #f5f5f5;
  padding-bottom: 120px; // 为底部按钮留出空间

  .form-content {
    background: white;
    margin: 8px;
    border-radius: 8px;
    padding: 16px;
  }

  .footer-actions {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    background: white;
    border-top: 1px solid #e8e8e8;
    padding: 16px;
    box-shadow: 0 -2px 8px rgba(0, 0, 0, 0.1);
    z-index: 1000;

    .action-buttons {
      display: flex;
      justify-content: flex-end;
      gap: 12px;

      .cancel-btn {
        background: white;
        border: 2px solid #d9d9d9;
        color: #434343;
        padding: 12px 20px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        min-width: 100px;
        height: 44px;
        text-align: center;
        line-height: 20px;
        transition: all 0.2s ease;

        &:active {
          background: #f5f5f5;
          border-color: #bfbfbf;
        }
      }

      .submit-btn {
        background: #1890ff;
        color: white;
        padding: 12px 20px;
        border-radius: 8px;
        font-size: 14px;
        font-weight: 500;
        min-width: 100px;
        height: 44px;
        text-align: center;
        line-height: 20px;
        border: none;
        transition: all 0.2s ease;

        &:active {
          background: #096dd9;
          transform: translateY(1px);
        }
      }
    }
  }
}
</style>